<?php
App::uses('AppModel', 'Model');

class Config extends AppModel {
    public $hasMany = array(
    'Image' => array(
      'className' => 'Attachment',
      'foreignKey' => 'foreign_key',
      'order' => 'id DESC',
      'conditions' => array(
        'Image.model' => 'Config',
        'Image.filetype' => 'image'
      ),
    ),
  );

  public function createWithAttachments($data) {
    // Sanitize your images before adding them
    $images = array();
    if (!empty($data['Image'][0])) {
      foreach ($data['Image'] as $i => $image) {
        if (is_array($data['Image'][$i])) {
          // Force setting the `model` field to this model
          $image['model'] = 'Config';
          $ext = substr($image['attachment']['name'], -4);
          $newName = inflector::slug($data['Config']['title']);
          $image['attachment']['name'] = $newName. $ext;
          // Unset the foreign_key if the user tries to specify it
          if (isset($image['foreign_key'])) {
            unset($image['foreign_key']);
          }
          $images[] = $image;
        }
      }
    }
    $data['Image'] = $images;

    //verifica se é cadastro ou edit para procurar arquivos anteriores e removê-los

    //die(debug($data));
    foreach($data['Image'] as $key=>$dataImage)
    {
      //die(debug($key));
      if(isset($data['Config']['id']) && !empty($data['Image'][$key]))
      {
        //die(debug($data));
        $imageBefore = $this->Image->find('first', array('conditions'=>array('Image.model'=>'Config', 'Image.foreign_key'=>$data['Config']['id'], 'Image.filetype'=>$data['Image'][$key]['filetype'])));
        if(!empty($imageBefore))
        $this->Image->delete($imageBefore['Image']['id']);
      }
    }

    // Try to save the data using Model::saveAll()
    $this->create();
    if ($this->saveAll($data)) {
      return true;
    }
    // Throw an exception for the controller
    //throw new Exception(__("This post could not be saved. Please try again"));
  }
}
